#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

void printCapacity(const vector<int> &con)
{
    cout << "size() = " << con.size() << endl;
    cout << "capacity() = " << con.capacity() << endl;
}

void test()
{
    cout << "sizeof(vector<int>) = " << sizeof(vector<int>) << endl;
    cout << "sizeof(vector<long>) = " << sizeof(vector<long>) << endl;

    vector<int> number = {1, 4, 6, 8, 9, 10, 5, 7};
    display(number);
    printCapacity(number);

    cout << endl << "在vector的尾部进行插入与删除" << endl;
    number.push_back(22);
    number.push_back(33);
    display(number);
    printCapacity(number);
    number.pop_back();
    display(number);
    printCapacity(number);

    //为何vector不支持在头部进行插入与删除呢?
    //因为vector是一端开口，如果在头部进行插入与删除，会导致后面的元素都
    //会受到影响，在头部插入一个元素，会导致后面的元素都会后移；在头部删除
    //一个元素，也会将后面的元素全部前移，这样在头部进行插入与删除的时候
    //效率比较低，O(N)

    cout << endl << "获取vector中的第一个元素的首地址" << endl;
    &number;//error,得不到第一个元素的首地址
    &*number.begin();//ok
    &number[0];//ok
    int *pdata = number.data();//ok

    cout << endl << "在vector的任意位置进行插入" << endl;
    auto it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, 111);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    //原因:vector在insert操作的时候，有可能会导致底层发生扩容操作，然后迭代
    //器还指向的是老的空间，老的空间已经回收了，所以迭代器就已经失效了
    //解决方案：重新置位迭代器
    cout << endl << endl;
    it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, 10, 200);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    cout << endl << endl;
    vector<int> vec = {333, 555, 444};
    it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, vec.begin(), vec.end());
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    cout << endl << endl;
    it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, {123, 789, 456});
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    cout << endl << "vector的清空操作" << endl;
    number.clear();
    number.shrink_to_fit();//回收多余的空间
    printCapacity(number);
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

